#include <stdlib.h>
#include <stdio.h>
#include "include/mysql.h"

#include <string.h>
#include "MySql.h"
#ifndef GCC_BUILD
#define GCC_BUILD   0
#endif

MYSQL * conn_ptr;
static int sql_flag=0;

//struct sql_storage{
//    const char* const field;   // 字段
//    const char* const format;  // 格式
//    char value[5120];          // 值
//};
struct sql_storage_item{
    char field[32];   // 字段
    char format[32];  // 格式
    char value[512];          // 值
};
/*
INSERT INTO `tbl_obd_4g`(`id`, `create_time`, `vin`, `prot`, `mil`, `status`, `ready`, `svin`, `cin`, `iupr`, `fault_total`, `fault`, `speed`, `kpa`, `nm`, `nmf`, `rpm`, `Lh`, `ppm_up`, `ppm_down`, `urea`, `kgh`, `SCR_in`, `SCR_out`, `DPF`, `coolant_temp`, `tank`, `gps_status`, `lat`, `lng`, `mil_total`, `Nm_mode`, `accelerator`, `oil_consume`, `urea_temp`, `urea_actual`, `urea_total`, `gas_temp`, `version`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11],[value-12],[value-13],[value-14],[value-15],[value-16],[value-17],[value-18],[value-19],[value-20],[value-21],[value-22],[value-23],[value-24],[value-25],[value-26],[value-27],[value-28],[value-29],[value-30],[value-31],[value-32],[value-33],[value-34],[value-35],[value-36],[value-37],[value-38],[value-39])

INSERT INTO `tbl_obd_4g`(`id`, `create_time`,
`vin`, `prot`, `mil`, `status`, `ready`, `svin`, `cin`, `iupr`, `fault_total`, `fault`,
`speed`, `kpa`, `nm`, `nmf`, `rpm`, `Lh`, `ppm_up`, `ppm_down`, `urea`, `kgh`, `SCR_in`, `SCR_out`, `DPF`, `coolant_temp`, `tank`, `gps_status`, `lat`, `lng`, `mil_total`,
`Nm_mode`, `accelerator`, `oil_consume`, `urea_temp`, `urea_actual`, `urea_total`, `gas_temp`, `version`
) VALUES (
[value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11],[value-12],[value-13],[value-14],[value-15],[value-16],[value-17],[value-18],[value-19],[value-20],[value-21],[value-22],[value-23],[value-24],[value-25],[value-26],[value-27],[value-28],[value-29],[value-30],[value-31],[value-32],[value-33],[value-34],[value-35],[value-36],[value-37],[value-38],[value-39])

 */
//static struct sql_storage sql_obd = {
//    .field = "vin, prot, mil, status, ready, svin, cin, iupr, fault_total, fault,",
//    .format = "",
//    .value = "",
//};
//static struct sql_storage sql_stream = {
//    .field = "speed, kpa, nm, nmf, rpm, Lh, ppm_up, ppm_down, urea, kgh, SCR_in, SCR_out, DPF, coolant_temp, tank, gps_status, lat, lng, mil_total, ",
//    .format = "",
//    .value = "",
//};
//static struct sql_storage sql_att = {
//    .field = "Nm_mode, accelerator, oil_consume, urea_temp, urea_actual, urea_total, gas_temp, version",
//    .format = "",
//    .value = "",
//};
static const struct sql_storage_item sql_report_items_format[] = {
    // "vin, prot, mil, status, ready, svin, cin, iupr, fault_total, fault,",
    {"UTC"   , "%s", ""},
    {"vin"   , "%s", ""},
    {"prot"  , "%d", ""},
    {"mil"   , "%d", ""},
    {"status", "%d", ""},
    {"ready" , "%d", ""},
    {"svin"  , "%s", ""},
    {"cin"   , "%s", ""},
    {"iupr"  , "%s", ""},
    {"fault_total", "%d", ""},
    {"fault", "%s", ""},
    // "speed, kpa, nm, nmf, rpm, Lh, ppm_up, ppm_down, urea, kgh, SCR_in, SCR_out, DPF, coolant_temp, tank, gps_status, lat, lng, mil_total, ",
    {"speed"   , "%f", ""},
    {"kpa"  , "%f", ""},
    {"nm"   , "%f", ""},
    {"nmf", "%f", ""},
    {"rpm" , "%f", ""},
    {"Lh"  , "%f", ""},
    {"ppm_up"   , "%f", ""},
    {"ppm_down"  , "%f", ""},
    {"urea", "%f", ""},
    {"kgh", "%f", ""},
    {"SCR_in"   , "%f", ""},
    {"SCR_out"  , "%f", ""},
    {"DPF"   , "%f", ""},
    {"coolant_temp", "%f", ""},
    {"tank" , "%f", ""},
    {"gps_status"  , "%d", ""},
    {"lat"   , "%f", ""},
    {"lon"  , "%f", ""},
    {"mil_total", "%f", ""},
    // "Nm_mode, accelerator, oil_consume, urea_temp, urea_actual, urea_total, gas_temp, version",
    {"Nm_mode"   , "%d", ""},
    {"accelerator"  , "%f", ""},
    {"oil_consume"   , "%f", ""},
    {"urea_temp", "%f", ""},
    {"urea_actual" , "%f", ""},
    {"urea_total"  , "%f", ""},
    {"gas_temp"   , "%f", ""},
    {"version"  , "%d", ""},
};
static const int sql_report_items_size = sizeof (sql_report_items_format)/sizeof (sql_report_items_format[0]);
static struct sql_storage_item sql_report_items[128];

// 存单个数据
int insert_item(const char* const field, const double value)
{
    int index=0;
    struct sql_storage_item *item=NULL;
    for(index=0; index<sql_report_items_size; index++)
    {
        item = &sql_report_items[index];
        if(0==strcmp(field, item->field))
        {
            sprintf(item->value, item->format, value);
            sql_flag=1;
            return 0;
        }
    }
    return -1;
}
int insert_item_string(const char* const field, const char* const string_value)
{
    int index=0;
    struct sql_storage_item *item=NULL;
    for(index=0; index<sql_report_items_size; index++)
    {
        item = &sql_report_items[index];
        if(0==strcmp(field, item->field))
        {
            sprintf(item->value, "\"%s\"", string_value);
            sql_flag=1;
            return 0;
        }
    }
    return -1;
}
int insert_item_int(const char* const field, const int value)
{
    int index=0;
    struct sql_storage_item *item=NULL;
    for(index=0; index<sql_report_items_size; index++)
    {
        item = &sql_report_items[index];
        if(0==strcmp(field, item->field))
        {
            sprintf(item->value, item->format, value);
            sql_flag=1;
            return 0;
        }
    }
    return -1;
}
static char sql_field[1024*10];   // 字段
static char sql_value[1024*10];   // 值
static char sql_query[1024*10];   // SQL语句
// 存入数据库
int insert_sql(void)
{
    int index=0;
    int ret=0;
    char *_field=NULL;
    char *_value=NULL;
    struct sql_storage_item *item=NULL;
    if(0==sql_flag) return 0;
//    memset(sql_field, 0, sizeof (sql_field));
//    memset(sql_value, 0, sizeof (sql_value));
//    memset(sql_query, 0, sizeof (sql_query));
    for(index=0; index<sql_report_items_size-1; index++)
    {
        item = &sql_report_items[index];
        _field=&sql_field[strlen(sql_field)];
        _value=&sql_value[strlen(sql_value)];
        sprintf(_field, "%s, ", item->field);
        sprintf(_value, "%s, ", item->value);
    }
    item = &sql_report_items[index];
    _field=&sql_field[strlen(sql_field)];
    _value=&sql_value[strlen(sql_value)];
    sprintf(_field, "%s", item->field);
    sprintf(_value, "%s", item->value);
    // "INSERT INTO tbl_obd_4g(vin,lat,lng) VALUES(%s,%f,%f)"
    // 合成 SQL 语句
    sprintf(sql_query, "INSERT INTO tbl_obd_4g(%s) VALUES(%s)", sql_field, sql_value);
    //printf("sql_query:%s \n", sql_query); fflush(stdout);
#if GCC_BUILD
    ret = mysql_query(conn_ptr,sql_query);
    if(!ret)
    {
        //printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(conn_ptr));
        return 0;
    }
    else
    {
        printf("Connect Erro:%d %s\n",mysql_errno(conn_ptr),mysql_error(conn_ptr));
    }
#endif
    return -1;
}

void MySqlInit(void)
{
//	MYSQL * conn_ptr;
    //struct sql_storage_item *item=NULL;
    //int index = 0;
#if GCC_BUILD
    conn_ptr = mysql_init(NULL);
    if(!conn_ptr)
    {
        fprintf(stderr,"mysql init failed\n");
    }else
    {
        conn_ptr =mysql_real_connect(conn_ptr,"localhost","xcwy","xcwy_data","xcwy",3306,NULL,0);
    }
#endif
//    memset(sql_obd.value, 0, sizeof (sql_obd.value));
//    memset(sql_stream.value, 0, sizeof (sql_stream.value));
//    memset(sql_att.value, 0, sizeof (sql_att.value));
//    for(index=0; index<sql_report_items_size; index++)
//    {
//        item = &sql_report_items[index];
//        memset(item->value, 0, sizeof (item->value));
//    }
    memset(sql_report_items, 0, sizeof (sql_report_items));
    memcpy(sql_report_items, sql_report_items_format, sizeof (sql_report_items_format));
    memset(sql_field, 0, sizeof (sql_field));
    memset(sql_value, 0, sizeof (sql_value));
    memset(sql_query, 0, sizeof (sql_query));
    sql_flag=0;
}
#if 0
void MySqlSeve(const uint8_t VIN[], double longitude, double latitude)
{
	int ret=0;
//	MYSQL * conn_ptr;
	int i=0;
	char VINEX[20];
	memset(VINEX,0,20);
	VINEX[0] = '\'';
	if(VIN[0] != '\0')	
	{
		for(i=0;i<17;i++)
		{	
			VINEX[i+1] = VIN[i];
		}
		VINEX[18]='\'';
	}else
	{
		VINEX[1]='N';
		VINEX[2]='U';
		VINEX[3]='L';
		VINEX[4]='L';
		VINEX[5]='\'';		
	}
	char i_query[200];
	memset(i_query,0,200);
    sprintf(i_query,"INSERT INTO tbl_obd_4g(vin,lat,lng) VALUES(%s,%f,%f)",VINEX,latitude,longitude);

//	printf("%s \n",i_query);	
//	printf("sql:%s \n %d \n %d \n",VIN,longitude,latitude);
#if 0
//	conn_ptr = mysql_init(NULL);

	if(!conn_ptr)
	{
		fprintf(stderr,"mysql init failed\n");
	}else
	{
		conn_ptr =mysql_real_connect(conn_ptr,"localhost","xcwy","xcwy_data","xcwy",3306,NULL,0);

		if(conn_ptr)
		{
		        printf("connection success \n");
		}
	}
#else
#if GCC_BUILD
    ret = mysql_query(conn_ptr,i_query);
    if(!ret)
    {
        printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(conn_ptr));
    }else
    {
        printf("Connect Erro:%d %s\n",mysql_errno(conn_ptr),mysql_error(conn_ptr));
    }
#endif
#endif

}
#endif

void MySqlClose(void)
{
#if GCC_BUILD
	mysql_close(conn_ptr);
#endif
}

